<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */

namespace app\index\util;

use app\index\model\Commodity;
use app\index\model\Order;
use app\index\model\OrderCommodity;

class OrderCount
{
    private $redis;


    private $user;

    public function __construct()
    {
        $this->redis = Redis::getInstance();
        global $user;
        $this->user = $user;
    }

    public function userOrderCount(string $cid)
    {
        global $user;
        $commodity = Commodity::find($cid);
        $count = OrderCommodity::whereTime('create_time', '>', $commodity['limitation_time'])
            ->where('commodity_id', $cid)
            ->where('order_id', 'in', function ($query) use ($user) {
                $query->name('order')->where('user_id', $user['id'])->field('id');
            })
            ->where('after_status', 3)
            ->field('SUM(count) as count')
            ->find()->toArray();

        return $count['count'] ?? 0;
    }

    public function commodityByOrderCount($cid)
    {
//        订单状态: 1-待支付 2-待发货 3-已发货 4-已完结 5-已评价   6-删除 7-已收货 8-维权中 9-已维权 10-维权驳回 11-已关闭
        $user = $this->user;
        $count = OrderCommodity::where('commodity_id', $cid)
            ->where('order_id', 'in', function ($query) use ($user) {
                $query->name('order')->where('user_id', $user['id'])->field('id');
            })
            ->where('status', 'in', '1,2,3,4,5,7,8,9,10')
            ->field('SUM(count) as count')
            ->find()->toArray();
        return $count['count'] ?? 0;
    }

    public function commodityByTrolley($cid)
    {
        $num = 0;
        $items = $this->redis->hKeys(checkRedisKey('TROLLEY:' . $this->user['id']));
        foreach ($items as $key => $value) {
            $id = explode('-', $value)[0];
            if ("id:".$cid == $id) {
                $count = $this->redis->hGet(checkRedisKey('TROLLEY:' . $this->user['id']), $value);
                if ($count) {
                    $num += json_decode($count, true)['num'];
                }
            }
        }
        return $num;
    }
}